#include "postmessagerequest.h"

PostMessageRequest::PostMessageRequest(QObject *parent) :
    ExecutionObjectInterface(parent)
{
    urlPath_ = "http://pcw-textinclass.appspot.com/postMessagesClient";

    toNumber_ = "";
    message_ = "";
    cookieData_ = "";

    manager_ = NULL;
}

PostMessageRequest::PostMessageRequest(QString toNumber, QString message, QString timestamp, QString cookieData, QObject *parent)
    : ExecutionObjectInterface(parent)
{
    urlPath_ = "http://pcw-textinclass.appspot.com/postMessagesClient";

    toNumber_ = toNumber;
    message_ = message;
    timestamp_ = timestamp;

    cookieData_ = cookieData;

    manager_ = NULL;
}

PostMessageRequest::~PostMessageRequest()
{

}

void PostMessageRequest::doInBackground()
{
    manager_ = new QNetworkAccessManager(this);

    if (manager_ == NULL) {
        emit error("Unable to allocate access manager");
        emit processFinished();
        return;
    }

    QUrl url(urlPath_);
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/x-www-form-urlencoded");

    request.setRawHeader(tr("Cookie").toUtf8(), cookieData_.toUtf8());

    QByteArray data;
    QUrl params;

    params.addEncodedQueryItem("to_number", QUrl::toPercentEncoding(toNumber_));
    params.addEncodedQueryItem("message", QUrl::toPercentEncoding(message_));
    params.addEncodedQueryItem("timestamp", QUrl::toPercentEncoding(timestamp_));

    data.append(params.toString().mid(1));

    connect(manager_, SIGNAL(finished(QNetworkReply*)), this, SLOT(onNetworkReply(QNetworkReply*)));

    manager_->post(request, data);
}

void PostMessageRequest::onPostExecute()
{
    emit objectFinished();
}

void PostMessageRequest::onNetworkReply(QNetworkReply *reply)
{
    QString responseString = reply->readAll();

    if (responseString != "Success") {
        emit error(responseString);
    }

    emit processFinished();
}
